<template>
  <div class="item" style="height: 100%; width: 100%" ref="container">
    <div id="SexPie" :style="{ width: '100%', height: '100%' }"></div>
  </div>
</template>

<script>
import request from "@/util/request.js";
import * as echarts from "echarts";

export default {
  name: "SexPie",
  data() {
    return {
      chartInstance: null,
      echart: echarts,
      option: {},
      sexCount: [],
      legendFontSize: 12, // 初始图例文字大小
      resizeTimer: null // 定时器
    };
  },
  mounted() {
    this.initChart();
    this.getSexCount();
    this.getData();
    window.addEventListener("resize", this.handleResizeEnd);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResizeEnd);
  },
  methods: {
    getSexCount() {
      request.get("/info_account/getSexCount").then((res) => {
        this.sexCount.push(...res.data.data);
        this.getData();
      });
    },
    initChart() {
      this.chartInstance = this.echart.init(document.getElementById("SexPie"));
    },
    async getData() {
      await this.updateData();
    },
    updateData() {
      this.option = {
        title: {
          text: "男女比例",
          left: "center",
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          orient: "vertical",
          left: "left",
          textStyle: {
            fontSize: this.legendFontSize, // 设置图例文字大小
          },
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            radius: "80%",
            data: this.sexCount,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      this.chartInstance.setOption(this.option, true);
    },
    handleResizeEnd() {
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.chartInstance.resize();
        this.legendFontSize = Math.max(Math.floor(this.chartInstance.getWidth() / 30), 10);
        this.updateData(); // 重新渲染 echarts 图表
      }, 100); // 设置延迟时间，500ms
    },
  },
};
</script>

<style scoped>
</style>
